package com.ruohi.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.FieldsDocumentPart;
import org.apache.poi.hwpf.usermodel.Field;
import org.apache.poi.hwpf.usermodel.Fields;
import org.apache.poi.hwpf.usermodel.Range;

public class ReadAndWriteDoc {
	
	private URL base = this.getClass().getResource("");

	public void writeDoc(Map<String, String> map,String newFileName,String templateName) { 
		try {  
			//读取word模板
			String fileDir = new File(base.getFile(),"../../../../../email/").getCanonicalPath();
			FileInputStream in = new FileInputStream(new File(fileDir+"/template/"+templateName));
			HWPFDocument hdt = new HWPFDocument(in);
			Fields fields = hdt.getFields();
			Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN).iterator();   
			while(it.hasNext()){
				  System.out.println(it.next().getType());
			} 
			
			//读取word文本内容
			Range range = hdt.getRange();
			//替换文本内容
			for (Map.Entry<String,String> entry:map.entrySet()) {
				range.replaceText(entry.getKey(),entry.getValue());
			}    
			ByteArrayOutputStream ostream = new ByteArrayOutputStream();
			FileOutputStream out = new FileOutputStream(fileDir+"/source/"+newFileName,true);
			hdt.write(ostream);
            //输出字节流
			out.write(ostream.toByteArray());
			out.close();
			ostream.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public static void main(String[] args){
		ReadAndWriteDoc rawDoc = new ReadAndWriteDoc();
		Map<String, String> map=new HashMap<String, String>();
		map.put("NAME", "zhanghonglei");  // 公司名称
		map.put("MEM_NO", "zhanghonglei");  // 会员账号
		map.put("PASSW", "zhanghonglei"); // 密码
		map.put("STIME", "zhanghonglei"); // 开始时间
		map.put("ETIME", "zhanghonglei"); // 结束时间
		String fileName = ""+System.currentTimeMillis();  // 生成的新文件名字 
		fileName += ".doc";
		System.out.println(fileName+"-----***");
		rawDoc.writeDoc(map,fileName,"YA.doc");
	}

}
